<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="产品类型" prop="firstLevel">
          <el-select
            v-model="queryParams.firstLevel"
            placeholder="请选择产品类型"
            style="width: 200px"
            @change="handleFirstLevelChange"
          >
            <el-option
              v-for="option in firstLevelOptions"
              :key="option"
              :label="option"
              :value="option"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="规格" prop="secondLevel">
          <el-select
            v-model="queryParams.secondLevel"
            placeholder="请选择规格"
            style="width: 200px"
            :disabled="!queryParams.firstLevel"
            @change="handleSecondLevelChange"
          >
            <el-option
              v-for="option in secondLevelOptions"
              :key="option"
              :label="option"
              :value="option"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工艺" prop="thirdLevel">
          <el-select
            v-model="queryParams.thirdLevel"
            placeholder="请选择工艺"
            style="width: 200px"
            :disabled="!queryParams.secondLevel"
            @change="handleThirdLevelChange"
          >
            <el-option
              v-for="option in thirdLevelOptions"
              :key="option"
              :label="option"
              :value="option"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-tag v-if="lastUpdateTime" type="info" size="small">
            更新时间：{{ lastUpdateTime }}
          </el-tag>
          <el-tag v-else type="warning" size="small">数据加载中...</el-tag>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>价格数据管理</span>
          <div>
            <el-radio-group v-model="editorMode" size="small">
              <el-radio-button label="table">表格模式</el-radio-button>
              <el-radio-button label="json">JSON模式</el-radio-button>
            </el-radio-group>
          </div>
        </div>
      </template>

      <div v-if="editorMode === 'table'">
        <div v-if="showPriceTable">
          <div class="mb-10px">
            <el-alert
              :title="`当前选择：${queryParams.firstLevel} - ${queryParams.secondLevel} - ${queryParams.thirdLevel}`"
              type="info"
              :closable="false"
            />
          </div>

          <div class="mb-10px">
            <el-alert
              title="操作提示：数量和价格都可以直接编辑，保存前会自动校验数据有效性"
              type="success"
              :closable="false"
              show-icon
            />
          </div>

          <el-table
            v-loading="loading"
            :data="priceTableData"
            border
            style="width: 100%"
            max-height="400"
          >
            <el-table-column prop="quantity" label="数量" min-width="180" align="center">
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.quantityValue"
                  :min="1"
                  :precision="0"
                  :step="1"
                  size="small"
                  style="width: 100%"
                  @change="handleQuantityChange(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="retailPrice" label="零售价(元)" min-width="160" align="center">
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.retailPrice"
                  :min="0"
                  :precision="2"
                  :step="0.01"
                  size="small"
                  style="width: 100%"
                  @change="handlePriceChange"
                />
              </template>
            </el-table-column>
            <el-table-column prop="memberPrice" label="会员价(元)" min-width="150" align="center">
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.memberPrice"
                  :min="0"
                  :precision="2"
                  :step="0.01"
                  size="small"
                  style="width: 100%"
                  @change="handlePriceChange"
                />
              </template>
            </el-table-column>
            <el-table-column prop="retailUnitPrice" label="零售单价(元)" width="150" align="center">
              <template #default="scope">
                <span>{{ formatPrice(scope.row.retailPrice / scope.row.quantityValue) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="memberUnitPrice" label="会员单价(元)" width="150" align="center">
              <template #default="scope">
                <span>{{ formatPrice(scope.row.memberPrice / scope.row.quantityValue) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" align="center">
              <template #default="scope">
                <el-button
                  size="small"
                  type="danger"
                  link
                  @click="handleDeleteRow(scope.$index, scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="mt-10px">
            <el-button size="small" type="primary" plain @click="handleAddRow">新增一行</el-button>
          </div>

          <div class="mt-20px text-center">
            <el-button type="primary" :loading="saving" @click="savePriceData">
              保存价格数据
            </el-button>
          </div>
        </div>

        <div v-else class="text-center" style="padding: 50px 0">
          <el-empty description="请选择产品类型、规格和工艺来查看价格数据" />
        </div>
      </div>

      <div v-else>
        <div class="mb-10px">
          <el-alert
            title="JSON编辑模式：直接编辑价格数据的JSON结构，请确保格式正确"
            type="warning"
            :closable="false"
            show-icon
          />
        </div>

        <div class="json-editor-container">
          <el-input
            v-model="jsonContent"
            type="textarea"
            :rows="20"
            class="json-textarea"
            placeholder="请输入JSON数据..."
            :validate-event="false"
          />
        </div>

        <div class="mt-10px">
          <el-button size="small" type="info" @click="formatJson">格式化JSON</el-button>
          <el-button size="small" type="success" @click="validateJson">验证JSON</el-button>
        </div>

        <div class="mt-20px text-center">
          <el-button type="primary" :loading="saving" @click="saveJsonData">保存JSON数据</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { computed, ref, onMounted, reactive, watch, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

import SysTextAPI from "@/api/system/sys-text.api";

defineOptions({
  name: "DigitalPriceMaintenance",
  inheritAttrs: false,
});

const queryFormRef = ref();

// 缓存相关常量
const CACHE_KEYS = {
  PRICE_DATA: "digital_price_data",
  LAST_UPDATE_TIME: "digital_price_update_time",
};

// 查询参数
const queryParams = reactive({
  firstLevel: "",
  secondLevel: "",
  thirdLevel: "",
});

// 价格数据相关
const priceData = ref({});
const originalPriceData = ref({});
const loading = ref(false);
const saving = ref(false);
const lastUpdateTime = ref("");
const firstLevelOptions = ref([]);
const secondLevelOptions = ref([]);
const thirdLevelOptions = ref([]);
const priceTableData = ref([]);

// 编辑器模式和JSON内容
const editorMode = ref("table");
const jsonContent = ref("");

// 显示价格表格
const showPriceTable = computed(() => {
  return queryParams.firstLevel && queryParams.secondLevel && queryParams.thirdLevel;
});

// 从localStorage加载缓存数据
const loadCacheData = () => {
  try {
    const cachedPriceData = localStorage.getItem(CACHE_KEYS.PRICE_DATA);
    const cachedUpdateTime = localStorage.getItem(CACHE_KEYS.LAST_UPDATE_TIME);

    if (cachedPriceData && cachedUpdateTime) {
      priceData.value = JSON.parse(cachedPriceData);
      originalPriceData.value = JSON.parse(cachedPriceData);
      lastUpdateTime.value = cachedUpdateTime;
      firstLevelOptions.value = Object.keys(priceData.value);
      return true;
    }
    return false;
  } catch (error) {
    console.error("加载缓存数据失败:", error);
    return false;
  }
};

// 保存数据到localStorage
const saveCacheData = (data, updateTime) => {
  try {
    localStorage.setItem(CACHE_KEYS.PRICE_DATA, JSON.stringify(data));
    localStorage.setItem(CACHE_KEYS.LAST_UPDATE_TIME, updateTime);
  } catch (error) {
    console.error("保存缓存数据失败:", error);
  }
};

// 获取价格数据
const fetchPriceData = async () => {
  try {
    loading.value = true;
    // 先从缓存加载
    const hasCachedData = loadCacheData();

    // 检查服务器更新时间
    const serverUpdateTime = await SysTextAPI.getTextByKey("price_update");

    // 如果缓存数据存在且更新时间一致，直接使用缓存
    if (hasCachedData && serverUpdateTime === lastUpdateTime.value) {
      console.log("使用缓存数据，更新时间一致");
      return;
    }

    // 需要重新获取数据
    console.log("获取最新价格数据");
    const response = await SysTextAPI.getTextByKey("price");
    if (response) {
      priceData.value = JSON.parse(response);
      originalPriceData.value = JSON.parse(JSON.stringify(priceData.value));
      firstLevelOptions.value = Object.keys(priceData.value);
      lastUpdateTime.value = serverUpdateTime || new Date().toLocaleString();
      // 保存到缓存
      saveCacheData(priceData.value, lastUpdateTime.value);
    }
  } catch (error) {
    console.error("获取价格数据失败:", error);
    ElMessage.error("获取价格数据失败");

    // 如果服务器获取失败，尝试使用缓存数据
    const hasCachedData = loadCacheData();
    if (hasCachedData) {
      ElMessage.warning("服务器获取失败，使用缓存数据");
    }
  } finally {
    loading.value = false;
  }
};

// 处理第一级选择
const handleFirstLevelChange = (value) => {
  queryParams.firstLevel = value;
  queryParams.secondLevel = "";
  queryParams.thirdLevel = "";
  secondLevelOptions.value = [];
  thirdLevelOptions.value = [];
  priceTableData.value = [];

  if (value && priceData.value[value]) {
    secondLevelOptions.value = Object.keys(priceData.value[value]);
  }
};

// 处理第二级选择
const handleSecondLevelChange = (value) => {
  queryParams.secondLevel = value;
  queryParams.thirdLevel = "";
  thirdLevelOptions.value = [];
  priceTableData.value = [];

  if (
    value &&
    priceData.value[queryParams.firstLevel] &&
    priceData.value[queryParams.firstLevel][value]
  ) {
    thirdLevelOptions.value = Object.keys(priceData.value[queryParams.firstLevel][value]);
  }
};

// 处理第三级选择
const handleThirdLevelChange = (value) => {
  queryParams.thirdLevel = value;
  loadPriceTableData();
};

// 加载价格表格数据
const loadPriceTableData = () => {
  if (
    queryParams.firstLevel &&
    queryParams.secondLevel &&
    queryParams.thirdLevel &&
    priceData.value[queryParams.firstLevel] &&
    priceData.value[queryParams.firstLevel][queryParams.secondLevel] &&
    priceData.value[queryParams.firstLevel][queryParams.secondLevel][queryParams.thirdLevel]
  ) {
    const quantityPrices =
      priceData.value[queryParams.firstLevel][queryParams.secondLevel][queryParams.thirdLevel];

    priceTableData.value = Object.keys(quantityPrices).map((quantityKey) => {
      const quantityValue = parseInt(quantityKey.replace(/个$/, ""));
      const prices = quantityPrices[quantityKey];

      return {
        quantity: quantityKey,
        quantityValue: quantityValue,
        retailPrice: prices.零售价 || 0,
        memberPrice: prices.会员价 || 0,
        originalQuantity: quantityKey, // 保存原始数量键
      };
    });
  } else {
    priceTableData.value = [];
  }
};

// 处理价格变化
const handlePriceChange = () => {
  // 实时更新priceData
  updatePriceData();
};

// 处理数量变化
const handleQuantityChange = (row) => {
  if (row.quantityValue && row.quantityValue > 0) {
    const newQuantity = `${row.quantityValue}个`;
    const oldQuantity = row.originalQuantity;

    // 更新显示值
    row.quantity = newQuantity;

    // 如果数量发生变化，需要更新priceData
    if (oldQuantity !== newQuantity) {
      // 从原来的key删除数据
      if (
        oldQuantity &&
        queryParams.firstLevel &&
        queryParams.secondLevel &&
        queryParams.thirdLevel
      ) {
        const quantityPrices =
          priceData.value[queryParams.firstLevel]?.[queryParams.secondLevel]?.[
            queryParams.thirdLevel
          ];
        if (quantityPrices && quantityPrices[oldQuantity]) {
          delete quantityPrices[oldQuantity];
        }
      }

      // 更新originalQuantity
      row.originalQuantity = newQuantity;
    }

    // 更新priceData
    updatePriceData();
  }
};

// 删除行
const handleDeleteRow = async (index, row) => {
  try {
    await ElMessageBox.confirm("确认删除这一行数据吗？", "确认删除", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    // 从priceData中删除
    if (
      queryParams.firstLevel &&
      queryParams.secondLevel &&
      queryParams.thirdLevel &&
      priceData.value[queryParams.firstLevel] &&
      priceData.value[queryParams.firstLevel][queryParams.secondLevel] &&
      priceData.value[queryParams.firstLevel][queryParams.secondLevel][queryParams.thirdLevel]
    ) {
      const quantityPrices =
        priceData.value[queryParams.firstLevel][queryParams.secondLevel][queryParams.thirdLevel];

      delete quantityPrices[row.originalQuantity];
    }

    // 从表格数据中删除
    priceTableData.value.splice(index, 1);

    ElMessage.success("删除成功");
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除失败:", error);
    }
  }
};

// 新增行
const handleAddRow = () => {
  // 获取下一个合适的数量值
  const existingQuantities = priceTableData.value
    .map((row) => row.quantityValue)
    .filter((qty) => qty > 0)
    .sort((a, b) => a - b);

  let nextQuantity = 1;

  // 找到第一个可用的数量值
  while (existingQuantities.includes(nextQuantity)) {
    nextQuantity++;
  }

  // 添加新行
  const newRow = {
    quantity: `${nextQuantity}个`,
    quantityValue: nextQuantity,
    retailPrice: 0,
    memberPrice: 0,
    originalQuantity: `${nextQuantity}个`,
  };

  priceTableData.value.push(newRow);

  // 更新priceData
  updatePriceData();

  ElMessage.success("新增行成功，可直接编辑数量和价格");
};

// 更新价格数据到priceData
const updatePriceData = () => {
  if (queryParams.firstLevel && queryParams.secondLevel && queryParams.thirdLevel) {
    // 确保数据结构存在
    if (!priceData.value[queryParams.firstLevel]) {
      priceData.value[queryParams.firstLevel] = {};
    }
    if (!priceData.value[queryParams.firstLevel][queryParams.secondLevel]) {
      priceData.value[queryParams.firstLevel][queryParams.secondLevel] = {};
    }
    if (!priceData.value[queryParams.firstLevel][queryParams.secondLevel][queryParams.thirdLevel]) {
      priceData.value[queryParams.firstLevel][queryParams.secondLevel][queryParams.thirdLevel] = {};
    }

    const quantityPrices =
      priceData.value[queryParams.firstLevel][queryParams.secondLevel][queryParams.thirdLevel];

    priceTableData.value.forEach((row) => {
      if (row.originalQuantity) {
        quantityPrices[row.originalQuantity] = {
          零售价: row.retailPrice,
          会员价: row.memberPrice,
        };
      }
    });
  }
};

// 格式化价格显示
const formatPrice = (price) => {
  if (price === null || price === undefined || isNaN(price)) {
    return "0.00";
  }
  return Number(price).toFixed(2);
};

// 数据校验
const validateTableData = () => {
  const errors = [];
  const quantities = new Set();

  // 检查表格是否为空
  if (priceTableData.value.length === 0) {
    errors.push("价格表格不能为空，请至少添加一行数据");
    return errors;
  }

  for (let i = 0; i < priceTableData.value.length; i++) {
    const row = priceTableData.value[i];
    const rowIndex = i + 1;

    // 检查数量
    if (!row.quantityValue || row.quantityValue <= 0) {
      errors.push(`第${rowIndex}行：数量必须大于0`);
    }

    // 检查数量重复
    if (quantities.has(row.quantityValue)) {
      errors.push(`第${rowIndex}行：数量${row.quantityValue}重复`);
    } else {
      quantities.add(row.quantityValue);
    }

    // 检查零售价
    if (row.retailPrice < 0) {
      errors.push(`第${rowIndex}行：零售价不能为负数`);
    }

    // 检查会员价
    if (row.memberPrice < 0) {
      errors.push(`第${rowIndex}行：会员价不能为负数`);
    }

    // 检查会员价是否合理（一般应该小于等于零售价）
    if (row.memberPrice > row.retailPrice) {
      errors.push(`第${rowIndex}行：会员价不应该高于零售价`);
    }
  }

  return errors;
};

// JSON校验
const validateJsonData = (jsonString) => {
  try {
    JSON.parse(jsonString);
    return true;
  } catch (error) {
    ElMessage.error(`JSON格式错误: ${error.message}`);
    return false;
  }
};

// 格式化JSON
const formatJson = () => {
  try {
    const parsed = JSON.parse(jsonContent.value);
    jsonContent.value = JSON.stringify(parsed, null, 2);
    ElMessage.success("JSON格式化成功");
  } catch (error) {
    ElMessage.error(`JSON格式错误，无法格式化: ${error.message}`);
  }
};

// 验证JSON
const validateJson = () => {
  if (validateJsonData(jsonContent.value)) {
    ElMessage.success("JSON格式正确");
  }
};

// 监听价格数据变化，更新JSON编辑器
watch(
  () => priceData.value,
  () => {
    if (editorMode.value === "json") {
      nextTick(() => {
        jsonContent.value = JSON.stringify(priceData.value, null, 2);
      });
    }
  },
  { deep: true }
);

// 保存JSON编辑器内容
const saveJsonData = async () => {
  try {
    saving.value = true;

    const jsonString = jsonContent.value;

    if (!validateJsonData(jsonString)) {
      return;
    }

    // 确认保存
    await ElMessageBox.confirm("确认保存JSON数据吗？保存后将更新服务器上的数据。", "确认保存", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    // 解析JSON并保存到priceData
    const parsedJson = JSON.parse(jsonString);
    priceData.value = parsedJson;

    // 调用API保存数据
    const dataToSave = {
      fileKey: "price",
      fileValue: jsonString,
    };

    await SysTextAPI.saveOrUpdateDigitalTextByKey(dataToSave);

    // 更新原始数据
    originalPriceData.value = JSON.parse(JSON.stringify(priceData.value));

    // 更新缓存时间和下拉选项
    const newUpdateTime = new Date().toLocaleString();
    lastUpdateTime.value = newUpdateTime;
    firstLevelOptions.value = Object.keys(priceData.value);

    // 更新缓存
    saveCacheData(priceData.value, newUpdateTime);

    // 重置选择
    queryParams.firstLevel = "";
    queryParams.secondLevel = "";
    queryParams.thirdLevel = "";
    secondLevelOptions.value = [];
    thirdLevelOptions.value = [];
    priceTableData.value = [];

    ElMessage.success("JSON数据保存成功");
  } catch (error) {
    if (error !== "cancel") {
      console.error("保存JSON数据失败:", error);
      ElMessage.error("保存JSON数据失败");
    }
  } finally {
    saving.value = false;
  }
};

// 保存价格数据
const savePriceData = async () => {
  try {
    saving.value = true;

    // 数据校验
    const validationErrors = validateTableData();
    if (validationErrors.length > 0) {
      const errorMessage = validationErrors.join("\n");
      ElMessageBox.alert(errorMessage, "数据校验失败", {
        confirmButtonText: "确定",
        type: "error",
        dangerouslyUseHTMLString: false,
      });
      return;
    }

    // 确认保存
    await ElMessageBox.confirm("确认保存价格数据吗？保存后将更新服务器上的数据。", "确认保存", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    // 更新priceData确保数据同步
    updatePriceData();

    // 调用API保存数据
    const dataToSave = {
      fileKey: "price",
      fileValue: JSON.stringify(priceData.value),
    };

    await SysTextAPI.saveOrUpdateDigitalTextByKey(dataToSave);

    // 更新原始数据
    originalPriceData.value = JSON.parse(JSON.stringify(priceData.value));

    // 更新缓存时间
    const newUpdateTime = new Date().toLocaleString();
    lastUpdateTime.value = newUpdateTime;

    // 更新缓存
    saveCacheData(priceData.value, newUpdateTime);

    ElMessage.success("价格数据保存成功");
  } catch (error) {
    if (error !== "cancel") {
      console.error("保存价格数据失败:", error);
      ElMessage.error("保存价格数据失败");
    }
  } finally {
    saving.value = false;
  }
};

// 监听编辑器模式变化
watch(editorMode, (newValue) => {
  if (newValue === "json") {
    // 切换到JSON编辑器模式
    nextTick(() => {
      // 初始化JSON内容
      jsonContent.value = JSON.stringify(priceData.value, null, 2);
    });
  }
});

// 组件挂载时获取价格数据
onMounted(async () => {
  await fetchPriceData();
});
</script>

<style scoped>
.unit-price-display {
  margin-top: 4px;
  font-size: 12px;
  color: #909399;
  text-align: right;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-input-number .el-input__inner) {
  text-align: center;
}

:deep(.el-table td .el-input-number) {
  width: 100%;
}

:deep(.el-table td .el-input-number .el-input__inner) {
  text-align: center;
  padding: 0 5px;
}

.mb-10px {
  margin-bottom: 10px;
}

.mt-10px {
  margin-top: 10px;
}

.mt-20px {
  margin-top: 20px;
}

.text-center {
  text-align: center;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.json-editor-container {
  position: relative;
  height: auto;
  margin-bottom: 20px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.json-textarea {
  font-family: "Consolas", "Monaco", "Courier New", monospace;
  font-size: 14px;
  line-height: 1.5;
}

:deep(.json-textarea .el-textarea__inner) {
  font-family: "Consolas", "Monaco", "Courier New", monospace;
  font-size: 14px;
  line-height: 1.5;
  border: none;
  resize: vertical;
  min-height: 400px;
  background-color: #fafafa;
  padding: 15px;
}

:deep(.json-textarea .el-textarea__inner:focus) {
  border-color: #409eff;
  outline: 0;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}
</style>
